package com.ruoyi.puyu.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.puyu.domain.PuyuLesson;
import com.ruoyi.puyu.mapper.PuyuLessonMapper;
import com.ruoyi.puyu.service.IPuyuLessonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 课时Service业务层处理
 * 
 * @author wusongwen
 * @date 2024-05-01
 */
@Service
public class PuyuLessonServiceImpl implements IPuyuLessonService 
{
    private static final Logger logger = LoggerFactory.getLogger(PuyuLessonServiceImpl.class);
    @Autowired
    private PuyuLessonMapper puyuLessonMapper;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询课时
     * 
     * @param lessonId 课时主键
     * @return 课时
     */
    @Override
    public PuyuLesson selectPuyuLessonByLessonId(Long lessonId)
    {
        return puyuLessonMapper.selectPuyuLessonByLessonId(lessonId);
    }

    /**
     * 查询课时列表
     * 
     * @param puyuLesson 课时
     * @return 课时
     */
    @Override
    public List<PuyuLesson> selectPuyuLessonList(PuyuLesson puyuLesson)
    {
        return puyuLessonMapper.selectPuyuLessonList(puyuLesson);
    }

    @Override
    public int selectPuyuLessonStudentTotal(PuyuLesson puyuLesson) {
        return puyuLessonMapper.selectPuyuLessonStudentTotal(puyuLesson);
    }

    /**
     * 新增课时
     * 
     * @param puyuLesson 课时
     * @return 结果
     */
    @Override
    public int insertPuyuLesson(PuyuLesson puyuLesson)
    {
        puyuLesson.setCreateBy(SecurityUtils.getUsername());
        puyuLesson.setCreateTime(DateUtils.getNowDate());
        String lockKey = buildLockKey(puyuLesson);
        boolean isLocked = redisCache.setIfAbsent(lockKey, "locked", 30, TimeUnit.MINUTES);
        if (!isLocked) {
            throw new ServiceException(MessageUtils.message("lesson.duplicate.submit"));
        }
        // 校验当天同一教练同一场馆同一班次是否已经存在课时
        PuyuLesson puyuLessonTemp = new PuyuLesson();
        puyuLessonTemp.setCoachId(puyuLesson.getCoachId());
        puyuLessonTemp.setClassesId(puyuLesson.getClassesId());
        puyuLessonTemp.setDelFlag("0");
        puyuLessonTemp.getParams().put("beginTime", DateUtils.parseDateToStr(DateUtils.YYYYMMDD,puyuLesson.getCreateTime()));
        puyuLessonTemp.getParams().put("endTime", DateUtils.parseDateToStr(DateUtils.YYYYMMDD,puyuLesson.getCreateTime()));
        List<PuyuLesson> list = puyuLessonMapper.selectPuyuLessonList(puyuLessonTemp);
        if (!list.isEmpty()) {
            logger.info("当日当前班次课时已存在，教练编号：{}, 场馆ID: {}, 班次ID: {}", puyuLesson.getCoachId(), puyuLesson.getStadiumId(), puyuLesson.getClassesId());
            throw new ServiceException(MessageUtils.message("lesson.exists"));
        }

        return puyuLessonMapper.insertPuyuLesson(puyuLesson);
    }

    /**
     * 修改课时
     * 
     * @param puyuLesson 课时
     * @return 结果
     */
    @Override
    public int updatePuyuLesson(PuyuLesson puyuLesson)
    {
        // 校验当天同一教练同一场馆同一班次是否已经存在课时
        PuyuLesson puyuLessonTemp = new PuyuLesson();
        puyuLessonTemp.setCoachId(puyuLesson.getCoachId());
        puyuLessonTemp.setClassesId(puyuLesson.getClassesId());
        puyuLessonTemp.getParams().put("beginTime", DateUtils.parseDateToStr(DateUtils.YYYYMMDD,puyuLesson.getCreateTime()));
        puyuLessonTemp.getParams().put("endTime", DateUtils.parseDateToStr(DateUtils.YYYYMMDD,puyuLesson.getCreateTime()));
        List<PuyuLesson> list = puyuLessonMapper.selectPuyuLessonList(puyuLessonTemp);
        if (!list.isEmpty() && list.get(0).getLessonId().compareTo(puyuLesson.getLessonId())!=0) {
            logger.info("当日当前班次课时已存在，教练编号：{}, 场馆ID: {}, 班次ID: {}", puyuLesson.getCoachId(), puyuLesson.getStadiumId(), puyuLesson.getClassesId());
            throw new ServiceException(MessageUtils.message("lesson.exists"));
        }

        puyuLesson.setUpdateTime(DateUtils.getNowDate());
        return puyuLessonMapper.updatePuyuLesson(puyuLesson);
    }

    /**
     * 批量删除课时
     * 
     * @param lessonIds 需要删除的课时主键
     * @return 结果
     */
    @Override
    public int deletePuyuLessonByLessonIds(Long[] lessonIds)
    {
        return puyuLessonMapper.updatePuyuLessonByLessonIds(lessonIds);
    }

    /**
     * 删除课时信息
     * 
     * @param lessonId 课时主键
     * @return 结果
     */
    @Override
    public int deletePuyuLessonByLessonId(Long lessonId)
    {
        return puyuLessonMapper.deletePuyuLessonByLessonId(lessonId);
    }

    /**
     * 构建课时信息key，同一天同一个教练同一个班次只能有一条记录，不可能同时在不同的场馆
     * @param puyuLesson
     * @return
     */
    private String buildLockKey(PuyuLesson puyuLesson) {
        return String.format("lock:lesson:%d:%d:%s",
                puyuLesson.getCoachId(),
                puyuLesson.getClassesId(),
                DateUtils.parseDateToStr(DateUtils.YYYYMMDD, puyuLesson.getCreateTime())
        );
    }
}
